class Request {
  constructor(options = {}) {
    this.baseURL = options.baseURL || '';
    this.timeout = options.timeout || 6000;
  }

  request(options = {}) {
    options.url = this.baseURL + options.url;
    options.timeout = options.timeout || this.timeout;
    options.method = options.method || 'GET';

    // 兼容 headers 传递
    if (options.headers) {
      options.header = options.headers;
      delete options.headers;
    }

    // 兼容 application/x-www-form-urlencoded 字符串直接传递
    // 如果 data 是字符串，直接传递，不做任何处理
    // 如果 data 是对象，uni.request 会自动处理为 JSON

    return new Promise((resolve, reject) => {
      options.success = (response) => {
        // 响应拦截
        resolve(response.data);
      };

      options.fail = (error) => {
        console.error(`[Error] ${options.method} ${options.url}`, error);
        reject(error);
      };

      uni.request(options);
    });
  }

  get(url, params = {}) {
    return this.request({
      url,
      method: 'GET',
      params
    });
  }

  post(url, data = {}, config = {}) {
    // 允许第三个参数传递 headers 或其它 uni.request 配置
    return this.request({
      url,
      method: 'POST',
      data,
      ...config
    });
  }

  put(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'PUT',
      data,
      ...options
    });
  }

  delete(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'DELETE',
      data,
      ...options
    });
  }
}

// 保存会话信息
export function setSession(sessionData) {
  if (!sessionData) return;
  
  // 保存cookies
  if (sessionData.cookies && sessionData.cookies.length) {
    uni.setStorageSync('cookies', JSON.stringify(sessionData.cookies));
  }
  
  // 保存sessionId
  if (sessionData.sessionId) {
    uni.setStorageSync('sessionId', sessionData.sessionId);
  }
}

// 获取会话信息
export function getSession() {
  const cookies = uni.getStorageSync('cookies');
  const sessionId = uni.getStorageSync('sessionId');
  
  return {
    cookies: cookies ? JSON.parse(cookies) : [],
    sessionId
  };
}

export default Request; 